package com.h3c.gm.schedule.task

import com.alibaba.fastjson.JSONArray
import com.alibaba.fastjson.JSONObject
import com.h3c.gm.common.constant.ScheduleURI
import com.h3c.gm.common.utils.SpringContextUtil
import com.h3c.gm.common.utils.UUIDUtils
import com.h3c.gm.entity.DO.BusStorageSpecDO
import com.h3c.gm.common.constant.HostOrgkeyPair
import com.h3c.gm.common.utils.HttpUtils
import com.h3c.gm.service.BusStorageSpecService
import org.slf4j.Logger
import org.slf4j.LoggerFactory

/**
 * Created by d14287 on 2017/7/7.
 */
class StorageTask implements Runnable {
    static Logger logger = LoggerFactory.getLogger(StorageTask.class)
    HostOrgkeyPair hostOrgkeyPair
    BusStorageSpecService storageSpecService = SpringContextUtil.getBean(BusStorageSpecService.class)

    @Override
    void run() {
        Optional<JSONArray> optional = HttpUtils.httpGet(hostOrgkeyPair.getProc() + '://' + hostOrgkeyPair.getHost() + ScheduleURI.storage_api_uri.replace('{host}', hostOrgkeyPair.getHost()))
        if (!optional.isPresent()) {
            return
        }
        storageSpecService.deleteByOrgkey(hostOrgkeyPair.name())
        JSONArray arrays = optional.get()
        for (int i = 0; i < arrays.size(); i++) {
            JSONObject object = arrays.getJSONObject(i)
            BusStorageSpecDO storageSpecDO = new BusStorageSpecDO()
            storageSpecDO.setId(UUIDUtils.generateUUID())
            storageSpecDO.setCreatetime(object.getDate('createtime'))
            storageSpecDO.setSize(object.getLong('size'))
            storageSpecDO.setStatus(object.getString('status'))
            storageSpecDO.setUserid(object.getString('userId'))
            storageSpecDO.setOrgkey(hostOrgkeyPair.name())
            storageSpecService.insert(storageSpecDO)
        }
    }

    StorageTask(HostOrgkeyPair hostOrgkeyPair) {
        this.hostOrgkeyPair = hostOrgkeyPair
    }
}
